import React, { Component } from 'react'

class LazyImage extends Component {
    render() {
        return (
            <div ref="scrollImg" className={this.props.className}>
                {this.props.children}
            </div>
        )
    }

    //滚动的函数
    scroll = () => {
        let imgs = [...this.scrollImg.querySelectorAll('img')];
        if(!imgs.length){
            return;
        }

        let {imgSrc} = this.props.options;

        imgs.forEach(imgDom => {
            if(this.scrollImg.scrollTop + this.clientHeight > imgDom.offsetTop){
                let url = imgDom.getAttribute(imgSrc);
                imgDom.setAttribute('src',url);
            }
        })
    }

    componentDidMount(){
        this.scrollImg = this.refs.scrollImg;
        //获取可视区域的高度
        this.clientHeight = this.scrollImg.clientHeight;
        // 添加滚动事件
        this.scrollImg.addEventListener('scroll',this.scroll);
        this.scroll();
    }

    //组件卸载前
    componentWillUnmount() {
        this.scrollImg.removeEventListener('scroll',this.scroll);
    }

    //滚动到指定位置 
    scrollToElement = (ind) => {
        let divs = this.scrollImg.querySelectorAll('div')[ind];
        this.scrollImg.scrollTop = divs.offsetTop;
    }
    
}

export default LazyImage




